package com.jy.appmarket.activity;

import android.app.ActionBar;
import android.content.Intent;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.jy.app.market.idata.data.Login;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.database.AppUpdateDatabase;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.screenlock.activity.BeautifulLockerSettingActivity;
import com.jy.appmarket.screenlock.prefs.LockPrefs;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.FeedbackAgent;
import com.umeng.fb.fragment.FeedbackFragment;

public class UserCenterActivity extends DownloadActivity implements OnClickListener{
	private static final int REQUEST_LOGIN_CODE = 10;
	private static final int REQUEST_LOGOUT_CODE = 11;
	private ImageView mHeadIconImg;
	private TextView mNickNameTv;
	private TextView mAppUpdateBadge;
	private ImageView mScreenLockNewFlag;
	private int mUpdateCount = Integer.MIN_VALUE;
	
	private ContentObserver mContentObserver = new ContentObserver(new Handler()) {
		@Override
		public void onChange(boolean selfChange) {
			invalidateUpdateBadgeIfNeeded();
		}

		@Override
		public void onChange(boolean selfChange, Uri uri) {
			invalidateUpdateBadgeIfNeeded();
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_center);
		
		initTitle();
		initViews();
		
		invalidateUpdateBadgeIfNeeded();
		getContentResolver()
		.registerContentObserver(AppUpdateDatabase.URI, false, mContentObserver);
	}

	private void initTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle("管理");
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
	}
	
	private void initViews() {
		mHeadIconImg = findViewById(R.id.head_icon);
		mNickNameTv = findViewById(R.id.nick_name);
		mAppUpdateBadge = findViewById(R.id.badge_app_update);
		mScreenLockNewFlag = findViewById(R.id.item_myscreenlock_new);
		
		findViewById(R.id.head_layout).setOnClickListener(this);
		findViewById(R.id.item_app_update).setOnClickListener(this);
		findViewById(R.id.item_apk_manager).setOnClickListener(this);
		findViewById(R.id.item_app_installed).setOnClickListener(this);
		findViewById(R.id.item_feedback).setOnClickListener(this);
		findViewById(R.id.item_myscreenlock).setOnClickListener(this);

		//测试
		findViewById(R.id.tv_test).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				startActivity(new Intent(UserCenterActivity.this,UserLoginActivity.class));
			}
		});
		
		showUserInfo();
	}
	
	private void showUserInfo() {
		if(AppMarketApplication.isLogin()) {
			Login login = AppMarketApplication.getLogin();
			if (!TextUtils.isEmpty(login.getIconUrl())) {
				ImageLoader.getInstance().displayImage(login.getIconUrl(), mHeadIconImg, new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true)
						.resetViewBeforeLoading(false).build());
			}
			if (!TextUtils.isEmpty(login.getNickName())) {
				mNickNameTv.setText(login.getNickName());
			} else if (!TextUtils.isEmpty(login.getPhoneNum())) {
				String phoneNum = login.getPhoneNum();
				if (phoneNum.length() > 7) {
					mNickNameTv.setText(phoneNum.substring(0, 3) + "****" + phoneNum.substring(7));
				} else {
					mNickNameTv.setText(phoneNum);
				}
			} else {
				mNickNameTv.setText("user" + login.getUserId());
			}
		} else {
			mHeadIconImg.setImageResource(R.drawable.icon_user_logout);
			mNickNameTv.setText(getResources().getString(R.string.click_login));
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.head_layout:
			if(AppMarketApplication.isLogin()) {
				startActivityForResult(new Intent(this, LogoutActivity.class), REQUEST_LOGIN_CODE);
			} else {
				startActivityForResult(new Intent(this, UserLoginActivity.class), REQUEST_LOGOUT_CODE);
				overridePendingTransition(R.anim.bottom_in, 0);
			}
			break;
		case R.id.item_app_update:
			startActivity(new Intent(this, AppUpdateActivity.class));
			break;
		case R.id.item_apk_manager:
			startActivity(new Intent(this, ApkFileManagerActivity.class));
			break;
		case R.id.item_app_installed:
			startActivity(new Intent(this, InstalledAppManagerActivity.class));
			break;
		case R.id.item_feedback:
			startUmengFeedback();
			break;
		case R.id.item_myscreenlock:
			startActivity(new Intent(this, BeautifulLockerSettingActivity.class));
			if(LockPrefs.isLockNewFlag(this)) {
				LockPrefs.setLockNewFlag(this, false);
			}
			break;
		default:
			break;
		}
	}
	
	private void startUmengFeedback() {
		Intent intent = new Intent(this, UmengFeedbackActivity.class);
		FeedbackAgent feedbackAgent = new FeedbackAgent(this);
        String id = feedbackAgent.getDefaultConversation().getId();
        intent.putExtra(FeedbackFragment.BUNDLE_KEY_CONVERSATION_ID, id);
        startActivity(intent);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		showUserInfo();
		if(LockPrefs.isLockNewFlag(this)) {
			mScreenLockNewFlag.setVisibility(View.VISIBLE);
		}else {
			mScreenLockNewFlag.setVisibility(View.GONE);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
	
	@Override
	protected void onDestroy() {
		getContentResolver().unregisterContentObserver(mContentObserver);
		super.onDestroy();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_LOGIN_CODE || requestCode == REQUEST_LOGOUT_CODE) {
			showUserInfo();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	protected void onPackageInstalled(String pkgName) {
		invalidateUpdateBadgeIfNeeded();
	}

	protected void onPackageUninstalled(String pkgName) {
		invalidateUpdateBadgeIfNeeded();
	}
	
	private void invalidateUpdateBadgeIfNeeded() {
		AppUpdateDatabase db = AppUpdateDatabase.getInstance(this);
		db.correctAppUpdatesDatas(this);
		int update = db.getCount(false);
		if (update <= 0) {
			update = Integer.MIN_VALUE;
		}

		if (update != mUpdateCount) {
			mUpdateCount = update;
			showUpdateBadge();
		}
	}
	
	private void showUpdateBadge() {
		if (mUpdateCount == Integer.MIN_VALUE) {
			mAppUpdateBadge.setVisibility(View.GONE);
		} else {
			mAppUpdateBadge.setVisibility(View.VISIBLE);
			mAppUpdateBadge.setText(String.valueOf(mUpdateCount));
		}
	}
}
